package test;

import common.Utils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;

import java.text.SimpleDateFormat;

public class PublishPage extends Utils {

    private static String URL = "http://113.44.92.31:65533/index.html";
    public PublishPage() {
        super(URL);
    }

    public void checkPublish() throws InterruptedException {
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"bit-forum-content\"]/div[1]/div/div/div[2]/div/a[1]")));
        driver.findElement(By.xpath("//*[@id=\"bit-forum-content\"]/div[1]/div/div/div[2]/div/a[1]")).click();
        Thread.sleep(100);
        //下拉框的自动化测试
        WebElement dropdown = driver.findElement(By.xpath("//*[@id=\"article_post_borad\"]"));
        Select select = new Select(dropdown);
        select.selectByVisibleText("经验分享");//选择文本内容为经验分享的元素
        //获取已选中的选项
        WebElement selectOption = select.getFirstSelectedOption();
        Thread.sleep(50);
        assert selectOption.getText().equals("经验分享");//获取选中的选项的元素并和预期结果进行断言判断

        //输入标题
        SimpleDateFormat titleDate = new SimpleDateFormat("HH:mm:ss");
        String titleName = titleDate.format(System.currentTimeMillis());
        driver.findElement(By.xpath("//*[@id=\"article_post_title\"]")).sendKeys("自动化测试中: " + titleName);

        //输入内容
        String contentName = titleDate.format(System.currentTimeMillis());
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"edit-article\"]/div[1]/div[6]/div[1]/div/div/div/div[5]/div/pre")));
        element = driver.findElement(By.xpath("//*[@id=\"edit-article\"]/div[1]/div[6]/div[1]/div/div/div/div[5]/div/pre"));
        new Actions(driver).click(element).sendKeys("自动化测试中: " + contentName).perform();

        //点击发布
        JavascriptExecutor js = (JavascriptExecutor)driver;
        element = driver.findElement(By.xpath("//*[@id=\"article_post_submit\"]"));
        js.executeScript("arguments[0].scrollIntoView(true);",element);
        Thread.sleep(500);
        element.click();

        //测试发布是否成功，且基本内容是否正确
        //选择经验分享类
        Thread.sleep(100);
        driver.findElement(By.xpath("//*[@id=\"topBoardList\"]/li[9]/a")).click();
        //进入第一篇帖子进行元素验证
        Thread.sleep(200);
        driver.findElement(By.xpath("//*[@id=\"artical-items-body\"]/div[1]/div/div[2]/div[1]/a")).click();
        Thread.sleep(200);
        assert driver.findElement(By.xpath("//*[@id=\"details_article_content_title\"]")).getText().equals("自动化测试中: " + titleName);
        Thread.sleep(100);
        assert driver.findElement(By.xpath("//*[@id=\"details_article_content\"]/p")).getText().equals("自动化测试中: " + contentName);
    }
}
